<?php

namespace app\controller;

use app\service\UserService;
use support\Response;
use think\facade\Db;

//登录控制器
class LoginController extends Base
{

    //登录
    public function index(): Response
    {
        //获取参数code
        $code = $this->request->post('code', '10001');
        //获取参数platform
        $platform = $this->request->post('platform', 0);

        // 启动事务
        Db::startTrans();

        try {
            $userService = new UserService();
            switch ($platform) {
                case 0://h5
                    $res = $userService->toLoginByCode($code, $platform);
                    break;
                case 1: //1微信小程序登陆
                    $res = $userService->toLoginByCode($code, $platform);
                    break;
                default:
                    Db::rollBack();
                    return $this->fail('暂不支持的登录方式');
            }

            if (!empty($res['code']) && $res['code'] == 1) {
                $token = $res['data']['token'];
                if (!$token) {
                    Db::rollBack();
                    return $this->fail("登录失败,请重试");
                }
                Db::commit();
                return $this->success($res['msg'], $res['data']);
            } else {
                Db::rollBack();
                return $this->fail($res['msg']);
            }

        } catch (\Exception $e) {
            Db::rollBack();
            return $this->fail("服务器异常".$e->getMessage());
        }
    }

}
